package org.example.stockdemo.controller;

import org.example.stockdemo.config.R;
import org.example.stockdemo.entity.Stock;
import org.example.stockdemo.entity.StockDetail;
import org.example.stockdemo.service.StockDetailService;
import org.example.stockdemo.service.StockService;
import org.example.stockdemo.service.TencentStockService;
import org.example.stockdemo.util.CacheUtil;
import org.example.stockdemo.vo.FundTrendItemListVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.List;

@RestController
@RequestMapping("/api")
public class StockController {

    @Autowired
    private TencentStockService tencentStockService;
    @Autowired
    private StockService stockService;
    @Autowired
    private StockDetailService stockDetailService;

    /**
     * 搜索股票
     */
    @GetMapping("/stock/isFlush")
    public R<Boolean> search() {
        CacheUtil.isFlush = CacheUtil.isFlush ? false : true;
        return R.ok(CacheUtil.isFlush);
    }

    /**
     * 搜索股票
     */
    @GetMapping("/stocks/search")
    public R<List<Stock>> search(@RequestParam String keyword) {
        if (keyword.length() < 3) {
            return null;
        }
        try {
            return R.ok(stockService.search(keyword));
        } catch (IOException e) {
            return R.fail(e.getMessage());
        }
    }

    /**
     * 批量获取股票实时行情
     *
     * @param stockCodes 股票代码列表，多个代码用逗号分隔
     * @return 股票代码到实时数据的映射
     */
    @PostMapping("/stocks/list")
    public R<List<StockDetail>> getBatchRealtimeQuotes(@RequestBody List<String> stockCodes) {
        List<StockDetail> quotes = tencentStockService.getBatchRealtimeQuotes(stockCodes, true);
        return R.ok(quotes);
    }

    /**
     * 获取单个股票的实时行情
     */
    @GetMapping("/stocks/detail/{stockCode}")
    public R<StockDetail> getStockRealtime(@PathVariable String stockCode) {
        StockDetail quotes = stockDetailService.getStockDetailByCode(stockCode);
        return R.ok(quotes);
    }

    /**
     * 获取股票分时线数据
     */
    @GetMapping("/stocks/minutedata/{stockCode}")
    public R<FundTrendItemListVO> getStockMinuteData(@PathVariable String stockCode) {
        FundTrendItemListVO minuteData = stockDetailService.getMinuteData(stockCode);
        return R.ok(minuteData);
    }

}